

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Cheney">
  <meta name="keywords" content="Coding">
  
    <meta name="description" content="父进程使用系统调用pipe()建立一个管道，然后使用系统调用fork()创建两个子进程.父进程用系统调用signal()来捕捉来自键盘的中断信号SIGINT（即按Ctrl+C键,）；当捕捉到中断信号后，父进程用系统调用kill()向两个子进程发出信号。">
<meta property="og:type" content="article">
<meta property="og:title" content="Linux下多进程通信（signal，pipe）">
<meta property="og:url" content="https://cheney822.gitee.io/2021/05/07/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F__Linux%E4%B8%8B%E5%A4%9A%E8%BF%9B%E7%A8%8B%E9%80%9A%E4%BF%A1%EF%BC%88signal%EF%BC%8Cpipe%EF%BC%89/index.html">
<meta property="og:site_name" content="Cheney blog">
<meta property="og:description" content="父进程使用系统调用pipe()建立一个管道，然后使用系统调用fork()创建两个子进程.父进程用系统调用signal()来捕捉来自键盘的中断信号SIGINT（即按Ctrl+C键,）；当捕捉到中断信号后，父进程用系统调用kill()向两个子进程发出信号。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://imgbed.cheney.cc/picgo/20210429185652706.png">
<meta property="article:published_time" content="2021-05-07T00:22:00.000Z">
<meta property="article:modified_time" content="2022-04-05T13:14:30.847Z">
<meta property="article:author" content="Cheney">
<meta property="article:tag" content="算法">
<meta property="article:tag" content="C语言">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://imgbed.cheney.cc/picgo/20210429185652706.png">
  
  
  <title>Linux下多进程通信（signal，pipe） - Cheney blog</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"cheney822.gitee.io","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":1},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.1"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Cheney Blog</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('https://imgbed.cheney.cc/Blog_config/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="Linux下多进程通信（signal，pipe）">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2021-05-07 08:22" pubdate>
        2021年5月7日 早上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      4.7k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      24 分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Linux下多进程通信（signal，pipe）</h1>
            
            <div class="markdown-body">
              <h2 id="题目描述："><a href="#题目描述：" class="headerlink" title="题目描述："></a>题目描述：</h2><ul>
<li>父进程使用系统调用pipe()建立一个管道，然后使用系统调用fork()创建两个子进程：子进程1和子进程2</li>
<li>子进程1每隔1秒通过管道向子进程2发送数据：I send message x times.（x初值为1，以后发送一次后做加一操作）</li>
<li>子进程2从管道读出信息，并显示在屏幕上</li>
<li>父进程用系统调用signal()来捕捉来自键盘的中断信号SIGINT（即按Ctrl+C键,）；当捕捉到中断信号后，父进程用系统调用kill()向两个子进程发出信号，</li>
<li>子进程捕捉到信号后分别输出如下信息后终止：<br>  Child Process 1 is killed by Parent!<br>  Child Process 2 is killed by Parent!</li>
<li>父进程等待两个子进程终止后，释放管道并输出如下的信息后终止<br>  Parent Process is Killed!<h2 id="算法设计："><a href="#算法设计：" class="headerlink" title="算法设计："></a>算法设计：</h2><h4 id="多进程："><a href="#多进程：" class="headerlink" title="多进程："></a>多进程：</h4>这里主要是利用系统调用fork：</li>
<li>fork是Linux下创建进程的一个系统调用<br>调用fork的进程为主进程，一次调用会产生一个子进程。</li>
<li>fork的特点：一次调用两次返回：<br>主进程和子进程的差异就从fork这条语句开始，fork给调用他的主进程的返回值是子进程的PID （若成功），给子进程的返回值是0，故可由此判断当前进程是子进程还是父进程，如：</li>
</ul>
<figure class="highlight cpp"><table><tr><td class="gutter"><div class="code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></div></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-type">int</span> pid = fork();<br><span class="hljs-keyword">if</span>(pid==<span class="hljs-number">0</span>)&#123;<br><span class="hljs-comment">//说明是子进程，这里写子进程的相关操作</span><br>&#125;<br><span class="hljs-keyword">else</span>&#123;<br><span class="hljs-comment">//说明是父进程，这里写父进程的相关操作</span><br>&#125;<br></code></pre></td></tr></table></figure>

<h5 id="如何创建多个子进程？"><a href="#如何创建多个子进程？" class="headerlink" title="如何创建多个子进程？"></a>如何创建多个子进程？</h5><p>错误的方法：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> i=<span class="hljs-number">0</span>;i&lt;<span class="hljs-number">10</span>:i++)<br>	fork();<br></code></pre></td></tr></table></figure>
<p>这显然不正确，因为不仅有父进程可以执行fork()语句，子进程也能执行，这就会导致实际创建的进程比预期的要多，因为有类似子进程的子进程存在。<br>避免这个问题也很简单，只在父进程执行fork()就行了，区分父子进程的方法上面已经给出。<br>我的具体实现代码：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-type">int</span> childpid[<span class="hljs-number">10</span>];<span class="hljs-comment">//用来保存所有进程的PID，0号是主进程</span><br>childpid[<span class="hljs-number">0</span>]=<span class="hljs-built_in">getpid</span>();<span class="hljs-comment">//012分别是父进程和两个子进程的pid</span><br><span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> i=<span class="hljs-number">1</span>;i&lt;=<span class="hljs-number">2</span>;i++)&#123;<br>		<span class="hljs-type">int</span> pid=fork();<br>		<span class="hljs-keyword">if</span>(pid!=<span class="hljs-number">0</span>)<br>			childpid[i] =pid;<br>		<span class="hljs-keyword">else</span>&#123;<br>			childpid[i] =<span class="hljs-built_in">getpid</span>();<br>			<span class="hljs-keyword">break</span>;<br>		&#125;<br>	&#125;<br></code></pre></td></tr></table></figure>
<h5 id="最终，主程序的逻辑大概如下："><a href="#最终，主程序的逻辑大概如下：" class="headerlink" title="最终，主程序的逻辑大概如下："></a>最终，主程序的逻辑大概如下：</h5><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><br><span class="hljs-keyword">if</span>(<span class="hljs-built_in">getpid</span>()==childpid[<span class="hljs-number">0</span>])&#123;<br>&#125;<br><span class="hljs-keyword">if</span>(<span class="hljs-built_in">getpid</span>()==childpid[<span class="hljs-number">1</span>])&#123;<br>&#125;<br><span class="hljs-keyword">if</span>(<span class="hljs-built_in">getpid</span>()==childpid[<span class="hljs-number">2</span>])&#123;<br>&#125;<br><br><br></code></pre></td></tr></table></figure>

<h4 id="信号机制："><a href="#信号机制：" class="headerlink" title="信号机制："></a>信号机制：</h4><div class="code-wrapper"><pre><code class="hljs">信号是在软件层次上对中断机制的一种模拟，是一种异步通信方式
</code></pre></div>
<p>使用signal()函数处理时，只需指出<strong>要处理的信号</strong>和<strong>处理函数</strong>即可。<br><strong>signal()原型：</strong><br><code>/*signal-handler*/* signal(int sig, /*signal-handler*/* handler); </code></p>
<ul>
<li>参数：<br>sig：要设置信号处理函数的信号。它可以是实现定义值或预定义的宏(见下方)：<br>handler：信号处理函数。这必须是下列之一：<br>&emsp;&emsp;SIG_DFL 宏。信号处理函数被设为默认信号处理函数。<br>&emsp;&emsp;SIG_IGN 宏。忽略信号。<br>&emsp;&emsp;指向函数指针。</li>
<li>返回值<br>成功时为先前的信号处理函数，失败时为 SIG_ERR （某些实现上能禁用设置信号处理函数）。</li>
<li>信号处理函数的预定义宏</li>
</ul>
<blockquote>
<p>SIGINT：ctrl+c 终止信号 　　<br>SIGQUIT：ctrl+\ 终止信号 　　<br>SIGTSTP:ctrl+z 暂停信号<br>SIGALRM：闹钟信号 收到此信号后定时结束，结束进程 　　<br>SIGCHLD：子进程状态改变，父进程收到信号 　　<br>SIGKILL：杀死信号</p>
</blockquote>
<ul>
<li>用户进程对信号的响应方式：<br>&emsp;&emsp;忽略信号（利用SIG_IGN 宏）<br>&emsp;&emsp;捕捉信号<br>&emsp;&emsp;执行缺省操作</li>
</ul>
<ul>
<li>其他需要的相关函数：<blockquote>
<p>int kill(pid_t pid, int sig);<br>　　功能：发送信号<br>　　参数：pid：指定进程<br>　　&emsp;&emsp;&emsp;sig：要发送的信号<br>　　返回值：成功 0；失败 -1<br>这里需要用到几个函数：</p>
</blockquote>
</li>
</ul>
<h5 id="程序功能的具体实现："><a href="#程序功能的具体实现：" class="headerlink" title="程序功能的具体实现："></a>程序功能的具体实现：</h5><ul>
<li>1.父进程接收Ctrl+C信号</li>
</ul>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-built_in">signal</span>(SIGINT,fun_pare);<span class="hljs-comment">//发出中断信号</span><br></code></pre></td></tr></table></figure>

<ul>
<li>2.父进程响应Ctrl+C：向子进程发出信号</li>
</ul>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">fun_pare</span><span class="hljs-params">(<span class="hljs-type">int</span> sig)</span><span class="hljs-comment">//父进程响应Ctrl C 信号函数</span></span><br><span class="hljs-function"></span>&#123;<br>	<span class="hljs-built_in">kill</span>(childpid[<span class="hljs-number">1</span>],SIGUSR1);<br>	<span class="hljs-built_in">kill</span>(childpid[<span class="hljs-number">2</span>],SIGUSR2);<br>&#125;<br></code></pre></td></tr></table></figure>

<ul>
<li>3.子进程接收父进程发来的信号</li>
</ul>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-built_in">signal</span>(SIGUSR1,fun_chid);<br><span class="hljs-built_in">signal</span>(SIGUSR2,fun_chid);<br></code></pre></td></tr></table></figure>
<p>注意在子进程中应该屏蔽Ctrl+C信号，否则，在父进程响应Ctrl+C时，子进程就会调用默认的响应函数而退出了：</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-built_in">signal</span>(SIGINT,SIG_IGN);<br></code></pre></td></tr></table></figure>


<ul>
<li>4.子进程对父进程发来的信号进行处理</li>
</ul>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">fun_chid</span><span class="hljs-params">(<span class="hljs-type">int</span> sig)</span><span class="hljs-comment">//子进程1响应信号函数</span></span><br><span class="hljs-function"></span>&#123;<br>	<span class="hljs-keyword">if</span>(sig==SIGUSR1)<br>		<span class="hljs-built_in">printf</span>(<span class="hljs-string">&quot;\nChild Process 1 is killed by parent!\n&quot;</span>);<br>	<span class="hljs-keyword">if</span>(sig==SIGUSR2)<br>	<span class="hljs-built_in">printf</span>(<span class="hljs-string">&quot;\nChild Process 2 is killed by parent!\n&quot;</span>);<br>		<br>	<span class="hljs-built_in">exit</span>(<span class="hljs-number">822</span>);<span class="hljs-comment">//默认正常退出返回0</span><br>&#125;<br></code></pre></td></tr></table></figure>
<p>这里利用响应函数的参数对接收到的函数进行判断，从而将两个进程的响应放在一块实现。</p>
<h4 id="管道通信："><a href="#管道通信：" class="headerlink" title="管道通信："></a>管道通信：</h4><ul>
<li>pipe函数的原型：<br>int pipe (int fd[2]); //成功返回0，出错返回-1<br>fd参数是数组/指针，可以带回两个值（文件描述符）,<br>fd[0]指向管道的读端,fd[1]指向管道的写端。fd[1]的输出是fd[0]的输入。</li>
<li>pipe通信（父子进程间）的流程：</li>
</ul>
<p>1.父进程创建管道，得到两个件描述符指向管道的两端<br>2.发进程关闭fd[1]（读端），利用write()向管道写入<br>3.收进程关闭fd[0]（写端），利用read()从管道读出</p>
<ul>
<li>我这里的实现：<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><span class="hljs-type">int</span> flg,fd[<span class="hljs-number">2</span>];<br>flg = <span class="hljs-built_in">pipe</span>(fd); <span class="hljs-comment">//创建管道</span><br>   <span class="hljs-keyword">if</span> (flg == <span class="hljs-number">-1</span>)<br>       <span class="hljs-built_in">perror</span>(<span class="hljs-string">&quot;pipe error&quot;</span>);<br>   <br>   <span class="hljs-type">int</span> *child，*msg，len；<br><span class="hljs-built_in">write</span>(fd[<span class="hljs-number">1</span>],child,len);<span class="hljs-comment">//表示向fd[1]写入child字符串的前len位</span><br><span class="hljs-built_in">read</span>(fd[<span class="hljs-number">0</span>],msg,<span class="hljs-built_in">sizeof</span>(msg))<span class="hljs-comment">//表示从fd[0]读出一个字符串</span><br></code></pre></td></tr></table></figure></li>
</ul>
<h2 id="整体实现代码："><a href="#整体实现代码：" class="headerlink" title="整体实现代码："></a>整体实现代码：</h2><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br></pre></td><td class="code"><pre><code class="hljs cpp"><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;signal.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;sys/wait.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;stdio.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;unistd.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;stdlib.h&gt;</span></span><br><span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string">&lt;string.h&gt;</span></span><br><br><br><span class="hljs-type">int</span> childpid[<span class="hljs-number">10</span>]=&#123;<span class="hljs-number">-1</span>,<span class="hljs-number">-1</span>,<span class="hljs-number">-1</span>,<span class="hljs-number">-1</span>&#125;,status=<span class="hljs-number">999</span>;<br><br>    <br><br><span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">fun_pare</span><span class="hljs-params">(<span class="hljs-type">int</span> sig)</span><span class="hljs-comment">//父进程响应Ctrl C 信号函数</span></span><br><span class="hljs-function"></span>&#123;<br>	<span class="hljs-built_in">kill</span>(childpid[<span class="hljs-number">1</span>],SIGUSR1);<br>	<span class="hljs-built_in">kill</span>(childpid[<span class="hljs-number">2</span>],SIGUSR2);<br>&#125;<br><span class="hljs-function"><span class="hljs-type">void</span> <span class="hljs-title">fun_chid</span><span class="hljs-params">(<span class="hljs-type">int</span> sig)</span><span class="hljs-comment">//子进程1响应信号函数</span></span><br><span class="hljs-function"></span>&#123;<br>	<span class="hljs-keyword">if</span>(sig==SIGUSR1)<br>		<span class="hljs-built_in">printf</span>(<span class="hljs-string">&quot;\nChild Process 1 is killed by parent!\n&quot;</span>);<br>	<span class="hljs-keyword">if</span>(sig==SIGUSR2)<br>	<span class="hljs-built_in">printf</span>(<span class="hljs-string">&quot;\nChild Process 2 is killed by parent!\n&quot;</span>);<br>		<br>	<span class="hljs-built_in">exit</span>(<span class="hljs-number">822</span>);<span class="hljs-comment">//默认正常退出返回0</span><br>&#125;<br><br><br><span class="hljs-function"><span class="hljs-type">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span>&#123;<br><br>	<span class="hljs-type">int</span> ret,fd[<span class="hljs-number">2</span>];<br>	ret = <span class="hljs-built_in">pipe</span>(fd); <span class="hljs-comment">//创建管道</span><br>    <span class="hljs-keyword">if</span> (ret == <span class="hljs-number">-1</span>)<br>        <span class="hljs-built_in">perror</span>(<span class="hljs-string">&quot;pipe error&quot;</span>);<br><br>	<br>	<br><br>	childpid[<span class="hljs-number">0</span>]=<span class="hljs-built_in">getpid</span>();<span class="hljs-comment">//012分别是父进程和两个子进程的pid</span><br><br>	<span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> i=<span class="hljs-number">1</span>;i&lt;=<span class="hljs-number">2</span>;i++)&#123;<br>		<span class="hljs-type">int</span> pid=fork();<br>		<span class="hljs-keyword">if</span>(pid!=<span class="hljs-number">0</span>)<br>			childpid[i] =pid;<br>		<span class="hljs-keyword">else</span>&#123;<br>			childpid[i] =<span class="hljs-built_in">getpid</span>();<br>			<span class="hljs-keyword">break</span>;<br>		&#125;<br>	&#125;<br><br><br>		<br><br>	<span class="hljs-keyword">if</span>(<span class="hljs-built_in">getpid</span>()==childpid[<span class="hljs-number">0</span>])&#123;<span class="hljs-comment">//父进程</span><br>		<span class="hljs-built_in">printf</span>(<span class="hljs-string">&quot;我是父进程,PID:%d PPID:%d\n&quot;</span>,<span class="hljs-built_in">getpid</span>(),<span class="hljs-built_in">getppid</span>());<br>		<span class="hljs-built_in">printf</span>(<span class="hljs-string">&quot;\t子进程1是：PID:%d\n&quot;</span>,childpid[<span class="hljs-number">1</span>]);<br>		<span class="hljs-built_in">printf</span>(<span class="hljs-string">&quot;\t子进程2是：PID:%d\n&quot;</span>,childpid[<span class="hljs-number">2</span>]);<br><br>		<span class="hljs-built_in">signal</span>(SIGINT,fun_pare);<span class="hljs-comment">//发出中断信号</span><br>			<br>		<span class="hljs-type">int</span> child_num = <span class="hljs-number">2</span>;<span class="hljs-comment">//子进程个数</span><br>		<span class="hljs-keyword">while</span>(child_num --)&#123;<br>		<span class="hljs-type">int</span> t = <span class="hljs-built_in">wait</span>(&amp;status);<span class="hljs-comment">//等待两个子进程结束</span><br>		<span class="hljs-built_in">printf</span>(<span class="hljs-string">&quot;一个进程结束了，他的 PID:%d 返回码 :%d\n&quot;</span>,t,status);<br>		&#125;<br>		<br><br>		<span class="hljs-built_in">printf</span>(<span class="hljs-string">&quot;Parent process is killed!\n&quot;</span>);<span class="hljs-comment">//两个子进程都结束后主进程才可以结束</span><br>		<span class="hljs-built_in">exit</span>(<span class="hljs-number">822</span>);<span class="hljs-comment">//默认正常退出返回0</span><br>	&#125;<br>	<span class="hljs-keyword">else</span>&#123;<span class="hljs-comment">//否则是子进程</span><br>		<span class="hljs-built_in">signal</span>(SIGINT,SIG_IGN);<br>		<span class="hljs-built_in">signal</span>(SIGUSR1,fun_chid);<br>		<span class="hljs-built_in">signal</span>(SIGUSR2,fun_chid);<br>	&#125;<br><br><br>	<span class="hljs-keyword">if</span>(<span class="hljs-built_in">getpid</span>()==childpid[<span class="hljs-number">1</span>])&#123;<span class="hljs-comment">//子进程1</span><br>		<span class="hljs-type">int</span> i=<span class="hljs-number">0</span>;<br>        <span class="hljs-built_in">close</span>(fd[<span class="hljs-number">0</span>]);<br>        <span class="hljs-type">char</span> child[<span class="hljs-number">100</span>]=<span class="hljs-string">&quot;I send message x times !\0&quot;</span>;<br>		<br>        <span class="hljs-keyword">while</span>(++i)<br>        &#123;<br>			child[<span class="hljs-number">15</span>] = <span class="hljs-string">&#x27;0&#x27;</span> + i;<br>            <span class="hljs-built_in">write</span>(fd[<span class="hljs-number">1</span>],child,<span class="hljs-built_in">strlen</span>(child)+<span class="hljs-number">1</span>);<br>            <span class="hljs-built_in">sleep</span>(<span class="hljs-number">1</span>);<br>        &#125;<br>	&#125;<br>	<span class="hljs-keyword">if</span>(<span class="hljs-built_in">getpid</span>()==childpid[<span class="hljs-number">2</span>])&#123;<span class="hljs-comment">//子进程2</span><br>	 	<span class="hljs-built_in">close</span>(fd[<span class="hljs-number">1</span>]);<br>        <span class="hljs-type">char</span> msg[<span class="hljs-number">100</span>];<br>        <span class="hljs-keyword">while</span>(<span class="hljs-number">1</span>)<br>        &#123;<br>            <span class="hljs-keyword">if</span>(<span class="hljs-built_in">read</span>(fd[<span class="hljs-number">0</span>],msg,<span class="hljs-built_in">sizeof</span>(msg)))<br>            	<span class="hljs-built_in">printf</span>(<span class="hljs-string">&quot;%s\n&quot;</span>,msg);<br>        &#125;<br>	&#125;	<br>	<span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;<br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="运行截图："><a href="#运行截图：" class="headerlink" title="运行截图："></a>运行截图：</h2><p><img src="https://imgbed.cheney.cc/picgo/20210429185652706.png" srcset="/img/loading.gif" lazyload alt="在这里插入图片描述"></p>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">操作系统</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/%E7%AE%97%E6%B3%95/">算法</a>
                    
                      <a class="hover-with-bg" href="/tags/C%E8%AF%AD%E8%A8%80/">C语言</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/05/08/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F__Linux%E6%96%87%E4%BB%B6%E7%B3%BB%E7%BB%9F%E5%AE%9E%E9%AA%8C%EF%BC%88C%E8%AF%AD%E8%A8%80%E5%AE%9E%E7%8E%B0%E6%96%B0%E5%BB%BA%E3%80%81%E6%89%93%E5%BC%80%E3%80%81%E5%85%B3%E9%97%AD%E3%80%81%E8%AF%BB%E5%86%99%E6%96%87%E4%BB%B6%E4%BB%A5%E5%8F%8A%E6%9F%A5%E6%94%B9%E6%96%87%E4%BB%B6%E6%9D%83%E9%99%90%EF%BC%89/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">Linux文件系统实验（C语言实现新建、打开、关闭、读写文件以及查改文件权限）</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/05/06/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F__%E8%BF%9B%E7%A8%8B%E9%80%9A%E4%BF%A1%E7%9A%84%E4%B8%89%E7%A7%8D%E6%96%B9%E5%BC%8F%EF%BC%88%E7%AE%A1%E9%81%93%E3%80%81%E6%B6%88%E6%81%AF%E7%BC%93%E5%86%B2%E9%98%9F%E5%88%97%E3%80%81%E5%85%B1%E4%BA%AB%E7%BC%93%E5%86%B2%E5%8C%BA%EF%BC%89/">
                        <span class="hidden-mobile">进程通信的三种方式（管道、消息缓冲队列、共享缓冲区）</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://cheney822.gitee.io/" target="_blank" rel="nofollow noopener"><span>备用网址</span></a> 
  </div>
  

  
  <!-- 备案信息 -->
  <div class="beian">
    <span>
      <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
        皖ICP备2022002876号-1
      </a>
    </span>
    
  </div>


  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    <script  src="/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  






  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
